﻿using UnityEngine;
using DG.Tweening;

namespace BToolkit.ExeUtils
{
    /// <summary>
    /// 两张图实现自动滚动
    /// </summary>
    public class PhotoSlider : MonoBehaviour
    {
        public TextureLoaderVideo photo1, photo2;

        TextureLoaderVideo currPhoto;
        float moveDuration = 1f;
        bool canMove = true;

        public void SetDefault(string photoPath)
        {
            photo2.gameObject.SetActive(false);
            currPhoto = photo1;
            currPhoto.gameObject.SetActive(true);
            currPhoto.LoadByFullPath(photoPath);
            SetSize(currPhoto);
            currPhoto.rectTransform.anchoredPosition = Vector2.zero;
        }

        public void Previous(string photoPath)
        {
            Move(photoPath, false);
        }

        public void Next(string photoPath)
        {
            Move(photoPath, true);
        }

        void Move(string photoPath, bool isForward)
        {
            if (!canMove) return;
            canMove = false;
            TextureLoaderVideo nextPhoto = currPhoto == photo1 ? photo2 : photo1;
            nextPhoto.LoadByFullPath(photoPath);
            SetSize(nextPhoto);
            float offsetX = (transform as RectTransform).sizeDelta.x;
            nextPhoto.rectTransform.anchoredPosition = new Vector2(isForward ? offsetX : -offsetX, 0);
            nextPhoto.gameObject.SetActive(true);
            currPhoto.transform.DOLocalMove(new Vector2(isForward ? -offsetX : offsetX, 0), moveDuration).SetEase(Ease.InOutExpo);
            nextPhoto.transform.DOLocalMove(new Vector2(0, 0), moveDuration).SetEase(Ease.InOutExpo).OnComplete(() =>
            {
                currPhoto.gameObject.SetActive(false);
                currPhoto = nextPhoto;
                canMove = true;
            });
        }

        void SetSize(TextureLoaderVideo photo)
        {
            if (photo.rawImage.texture)
            {
                Vector2 size = (transform as RectTransform).sizeDelta;
                size.y = size.x * photo.rawImage.texture.height / (float)photo.rawImage.texture.width;
                photo.rectTransform.sizeDelta = size;
            }
            else
            {
                Vector2 size = (transform as RectTransform).sizeDelta;
                size.y = size.x * 1080f / 1920f;
                photo.rectTransform.sizeDelta = size;
            }
        }
    }
}